<template>
  <div class="mavonEditor">
    <div>
      <el-input
          placeholder="请输入标题"
          v-model="article.title"
          maxlength="20"
          show-word-limit
          style="width:600px"
      >
      </el-input>
      <el-button type="primary" style="position: absolute;right:0;top:12px" @click="pushAritcle">上传文章</el-button>
    </div>
    <no-ssr>
      <mavon-editor ref="md" @imgAdd="imgAdd" v-model="mavonValue" @imgDel="$imgDel" subfield="false" defaultOpen="edit" style="height:700px;top:30px"/>
    </no-ssr>
   <div>
    <span style="float: left;margin:50px 0 0 0">
      <span style="font-size: 20px;line-height: 40px">上传附件:</span>
      <el-upload
          class="upload-demo"
          :auto-upload="false"
          :on-preview="handlePreview"
          :on-change="fileAdd"
          multiple
          :limit="3"
          :on-exceed="handleExceed"
          :on-remove="handleRemove"
          :before-remove="beforeRemove"
          :file-list="fileName"
          accept=".jpg,.jpeg,.png,.gif,.bmp,.pdf,.JPG,.JPEG,.PBG,.GIF,.BMP,.PDF,.c,.cpp,.zip,.rar,.java,.py,.css,.html,.js,.vue"
      >
        <el-button size="small" type="primary" @click="imgAdd">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">文件大小不超过10MB,最多可以上传3个附件</div>
      </el-upload>
    </span>

    <span style="float:right;margin-top:50px">
      <div style="font-size: 20px;margin: 10px 0 10px 0">添加标签:</div>
      <el-tag
          :key="tag"
          v-for="tag in tags.dynamicTags"
          closable
          :disable-transitions="false"
          @close="handleClose(tag)">
        {{tag}}
      </el-tag>
      <el-input
          class="input-new-tag"
          v-if="tags.inputVisible"
          v-model="tags.inputValue"
          ref="saveTagInput"
          size="small"
          @keyup.enter.native="handleInputConfirm"
          @blur="handleInputConfirm"
      >
      </el-input>
      <el-button v-else class="button-new-tag" size="small" @click="showInput">+ New Tag</el-button>
      <template>
        <el-checkbox-group v-model="tags.dynamicTags" style="margin-top:10px">
          <el-checkbox label="java"></el-checkbox>
          <el-checkbox label="python"></el-checkbox>
          <el-checkbox label="vue"></el-checkbox>
          <el-checkbox label="django"></el-checkbox>
          <el-checkbox label="c/c++"></el-checkbox>
          <el-checkbox label="sql"></el-checkbox>
        </el-checkbox-group>

        <el-checkbox-group v-model="tags.dynamicTags" style="margin-top:10px">
          <el-checkbox label="前端"></el-checkbox>
          <el-checkbox label="后端"></el-checkbox>
          <el-checkbox label="算法"></el-checkbox>
          <el-checkbox label="数据库"></el-checkbox>
          <el-checkbox label="移动开发"></el-checkbox>
        </el-checkbox-group>
      </template>

    </span>
  </div>
  </div>
</template>

<script>
import {mavonEditor} from "mavon-editor";
import "mavon-editor/dist/css/index.css";
import axios from "axios";
import qs from "qs";
import user from "@/store/user";
const markdownIt = mavonEditor.getMarkdownIt()
export default {
  // eslint-disable-next-line vue/multi-word-component-names
  name:"Markdown",
  components: {
    mavonEditor
  },
  props: {
      mdData: {
        type: String,
        default: ''
      },
      readonly: {
        type: Boolean,
        default: true
      },
  },

  data() {
    return {
      fileName:[],
      fileLink:[],
      article:{
        title:"",
        file: {},
        markdownIt,
        mavonValue: '',
      },
      tags:{
        dynamicTags: [],
        inputVisible: false,
        inputValue: ''
      }
    }
  },

  methods: {
    handleClose(tag) {
      this.tags.dynamicTags.splice(this.tags.dynamicTags.indexOf(tag), 1);
    },

    showInput() {
      this.tags.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleInputConfirm() {
      let inputValue = this.tags.inputValue;
      if (inputValue) {
        this.tags.dynamicTags.push(inputValue);
      }
      this.tags.inputVisible = false;
      this.tags.inputValue = '';
    },

    pushAritcle: function(){
      const userInfo = user.getters.getUser(user.state());

      if(userInfo===null){
        this.$message.warning("请先登录");
        this.$router.push('/login');
        return;
      }

      if(this.$store.state.isBan) {
        this.$message.error("您已被封禁！");
        return;
      }

      if(this.$refs.md.d_value===''){
        this.$message.warning("请输入文章内容");
        return;
      }

      if(this.article.title===''){
        this.$message.warning("请输入文章标题");
        return;
      }

      this.$axios({
        method: 'post',           /* 指明请求方式，可以是 get 或 post */
        url: '/article/publish',       /* 指明后端 api 路径，由于在 main.js 已指定根路径，因此在此处只需写相对路由 */
        data:({      /* 需要向后端传输的数据，此处使用 qs.stringify 将 json 数据序列化以发送后端 */
          authorID:userInfo.user.userID,
          authorName:userInfo.user.username,
          title: this.article.title,
          content_html: this.$refs.md.d_render,
          content_md:this.$refs.md.d_value,
          labels:this.tags.dynamicTags,
          fileNameList:this.fileName,
          attachmentUrlList:this.fileLink
        })
      })
          .then( res => {
            switch (res.data.code) {
              case 0:
                this.$message.success("文章发表成功！");
                this.$router.push('/');
                break;
              case 40100:
                this.$message.warning("请先登录");
                this.$router.push('/login')
                break;
            }
          })
    },

      // change() {  // 也可以接收 value 和 render参数 获取内容
      //   this.$emit('update:mdData', this.$refs.md.d_value);
      //   console.log(this.$refs.md.d_render);
      //   // console.log(this.$refs.md.d_value);  // markdown文本格式
      // },
      //

      imgAdd(pos, file){
        // 第一步.将图片上传到服务器.
        var formdata = new FormData();
        formdata.append("file", file);
        this.$axios({
          url: '/imgUpload',
          method: 'post',
          data: formdata,
          dataType:"json",
          cache:false,
          processData:false,
          headers: { 'Content-Type': 'multipart/form-data' },
        })
            .then(res => {
              // 第二步.将返回的url替换到文本原位置![...](0) -> ![...](url)
              if(res.data.code===0){
                window.alert("上传成功")
                this.$refs.md.$img2Url(pos, res.data.data);
              }
          /**
           * $vm 指为mavonEditor实例，可以通过如下两种方式获取
           * 1. 通过引入对象获取: `import {mavonEditor} from ...` 等方式引入后，`$vm`为`mavonEditor`
           * 2. 通过$refs获取: html声明ref : `<mavon-editor ref=md ></mavon-editor>，`$vm`为 `this.$refs.md`
           */
            })
      },

    fileAdd(item){
      var formdata = new FormData();
      var file=item.raw
      formdata.append("file", file);
      this.$axios({
        url: '/fileUpload',
        method: 'post',
        data: formdata,
        dataType:"json",
        cache:false,
        processData:false,
        headers: { 'Content-Type': 'multipart/form-data' },
      })
          .then(res => {
            // 第二步.将返回的url替换到文本原位置![...](0) -> ![...](url)
            if (res.data.code === 0) {
              window.alert("上传成功")
              this.fileLink.push(res.data.data.attachmentUrl)
              this.fileName.push(file.name)
            }
          })
    },
    handleRemove(file, fileList) {
      const i = this.fileName.findIndex((x) => x === file)
      this.fileName.splice(i, 1);
      this.fileLink.splice(i, 1);
      console.log(file, fileList);
    },
      handlePreview(file) {
        console.log(file);
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${ file.name }？`);
    }
    }
}
</script>

<style scoped>
.mavonEditor {
  width: 80%;
  height: 100%;
  margin: auto;
  position: absolute;
  top: 150px; left: 0; bottom: 0; right: 0;
}

.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
